# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.orderDao import OrderDaoYM
from com.zzh.dao_v2.orderDaoLYM import OrderDaoV3
import time
from . import app
from com.zzh.dao_v2.AuthTokenOperation import authTokenOperation
localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

CORS(app, supports_credentials=True)

"""
表名：zzh_Order

说明：会员信息表（包含个人和单位）
"""


@app.route('/queryOrderById', methods=['POST'])
def queryOrderByIdNoToken():
    if not request.json:
        abort(400)
    id = request.json.get("id")
    try:
        total_count,userCodeJSON = OrderDaoYM().queryOrderById(id)
        if total_count:
            return jsonify({"message": {"code": 1, "status": "queryOrder OK"}, "info": userCodeJSON})
        else:
            return jsonify({"info": [], "message": {"code": 1, "status": "No data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})



@app.route('/queryOrderById', methods=['POST'])
def queryOrderByOrderNoNoToken():
    if not request.json:
        abort(400)
    id = request.json.get("orderNo")
    try:
        total_count,userCodeJSON = OrderDaoYM().queryOrderByOrderNo(id)
        if total_count:
            return jsonify({"message": {"code": 1, "status": "queryOrder OK"}, "info": userCodeJSON})
        else:
            return jsonify({"info": [], "message": {"code": 1, "status": "No data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})



@app.route('/queryOrderByCondition', methods=['POST'])
def queryOrderByConditionNoToken():
        if not request.json:
            abort(400)



        try:
            page = request.json['page']
            pageIndex = page["pageIndex"]
            pageSize = page["pageSize"]
        except:
            return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})

        try:
            conditions = request.json['condition']
        except:
            return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
        try:
            multiSort = request.json['multiSort']
        except:
            return jsonify({"message": "未传入排序规则multiSort"})

        UserCodeJSON, total_count = OrderDaoYM().queryOrderByCondition(pageIndex=pageIndex, pageSize=pageSize,
                                                                           conditions=conditions, multiSort=multiSort)

        if total_count:
                return jsonify(
                    {"message": {"code": 1, "status": "queryOrder OK"}, "total": total_count, "info": UserCodeJSON})
        else:
                return jsonify({"info": [], "message": {"code": 0, "status": "No data"}})
        # except Exception, e:
        #         return jsonify({"message": {"code": 0, "info": str(e)}})




@app.route('/insertOrder_Old', methods=['POST'])
def insertOrderNoTokenOld():
        if not request.json:
            abort(400)



        order_no = OrderDaoYM().random_str()

        Info = {
            # 1-4，查询不同的表的时候，做好容错
            # 'order_no': request.json.get('order_no'),  # 前台传递
            'order_ip': request.remote_addr,  ##确定   读取request
            'order_type': request.json.get('order_type'),  # 前台传递     支付类型，1-pc,2-mobile
            'payment_id': request.json.get('payment_id'),
            # 前台传递     将支付记录与order_id绑定       我该拿这个做什么，传入进来，payment表没有任何符合的数据。
            'user_id': request.json.get('user_id'),  # 前台传递
            'coupon_id': request.json.get('coupon_id'),  # couponId  前台传递，用这个id区查询zzh_coupon表的相应记录，做好容错
            'payable_amount': request.json.get('payable_amount'),  # 前台传递  应付金额
            'real_amount': request.json.get('real_amount'),  # 前台传递  实际支付金额
            'order_amount': request.json.get('order_amount'),  # 前台传递  订单总金额
            'item_id': request.json.get('item_id'),  # 前台传递
            'trade_no': request.json.get('trade_no'),  # ???交易号担保支付用到  这个该从哪里取到  先置空

            'is_invoice': request.json.get('is_invoice', 0),  # 前台传递    是否开具发票，是否索要发票 默认0否，1是

            # 5-9
            'payment_fee': request.json.get('payment_fee', 0),  # ？？？支付手续费，先不管，置为空，数据库默认是  0.00
            'payment_status': request.json.get('payment_status', 1),  # 确定   支付状态1默认未支付     2已支付，支付时更新

            # 10-14
            'payment_time': request.json.get('payment_time'),  # 确定    支付时间，创建订单时候默认为空，然后 等到支付的时候再进行调用更新订单表进行更新
            'invoice_title': request.json.get('invoice_title', ""),
            # 发票抬头，如果is_invoice为1，根据这个invoice_title和userId添加zzh_invoice记录，同时绑定到invoice_id到order_id

            # 15-19
            'order_point': request.json.get('order_point'),
            # ？？？积分，这个积分将会和uesr_id和point_value积分值一起写入 zzh_point_log  这是收入的积分
            'is_coupon': request.json.get('is_coupon', 0),
            # ？？？优惠券，是否使用优惠券0否，1是  如果使用，则去查询zzh_coupon表？这个地方是不是需要绑定coupon_id？。如果不使用，是否直接置为空
            'order_message': request.json.get('order_message', ""),

            'order_status': request.json.get('order_status', 0),  # 确定    订单状态，默认为0生成订单，之后的状态等到  后续操作的时候更新
            'order_product_is_success': request.json.get('order_product_is_success', 0)
            # 确定    产品服务是否成功，默认0未成功,   1表示成功，等服务完成之后进行更新

        }

        if not Info:
            return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
        rs = OrderDaoYM().insertOrder(Info, order_no)
        if (rs == 1):
            return jsonify(
                {"message": {"code": 1, "info": "addOrder OK"}, "info": rs})  #
        else:
            return jsonify({"message": {"code": 0, "info": "addOrder Error"}, "rs": rs})  # 添加函数调用失败


@app.route('/insertOrder', methods=['POST'])
def insertOrderNoToken():
    if not request.json:
        abort(400)

    order_no = OrderDaoYM().random_str()

    Info = {
        # 1-4，查询不同的表的时候，做好容错
        # 'order_no': request.json.get('order_no'),  # 前台传递
        'order_ip': request.remote_addr,  ##确定   读取request
        'order_type': request.json.get('orderType'),  # 前台传递     支付类型，1-pc,2-mobile
        'payment_id': request.json.get('paymentId'),
        # 前台传递     将支付记录与order_id绑定       我该拿这个做什么，传入进来，payment表没有任何符合的数据。
        'user_id': request.json.get('userId'),  # 前台传递
        'coupon_id': request.json.get('couponId'),  # couponId  前台传递，用这个id区查询zzh_coupon表的相应记录，做好容错
        'payable_amount': request.json.get('payableAmount'),  # 前台传递  应付金额
        'real_amount': request.json.get('realAmount'),  # 前台传递  实际支付金额
        'order_amount': request.json.get('orderAmount'),  # 前台传递  订单总金额
        'item_id': request.json.get('itemId'),  # 前台传递
        'trade_no': request.json.get('tradeNo'),  # ???交易号担保支付用到  这个该从哪里取到  先置空

        'is_invoice': request.json.get('isInvoice', 0),  # 前台传递    是否开具发票，是否索要发票 默认0否，1是

        # 5-9
        'payment_fee': request.json.get('paymentFee', 0),  # ？？？支付手续费，先不管，置为空，数据库默认是  0.00
        'payment_status': request.json.get('paymentStatus', 1),  # 确定   支付状态1默认未支付     2已支付，支付时更新

        # 10-14
        'payment_time': request.json.get('paymentTime'),  # 确定    支付时间，创建订单时候默认为空，然后 等到支付的时候再进行调用更新订单表进行更新
        'invoice_title': request.json.get('invoiceTitle', ""),
        # 发票抬头，如果is_invoice为1，根据这个invoice_title和userId添加zzh_invoice记录，同时绑定到invoice_id到order_id

        # 15-19
        'order_point': request.json.get('orderPoint',0),
        # ？？？积分，这个积分将会和uesr_id和point_value积分值一起写入 zzh_point_log  这是收入的积分
        'is_coupon': request.json.get('isCoupon', 0),
        # ？？？优惠券，是否使用优惠券0否，1是  如果使用，则去查询zzh_coupon表？这个地方是不是需要绑定coupon_id？。如果不使用，是否直接置为空
        'order_message': request.json.get('orderMessage', ""),

        'order_status': request.json.get('orderStatus', 0),  # 确定    订单状态，默认为0生成订单，之后的状态等到  后续操作的时候更新
        'order_product_is_success': request.json.get('orderProductIsSuccess', 0),
        # 确定    产品服务是否成功，默认0未成功,   1表示成功，等服务完成之后进行更新
        'item_name': request.json.get('item_name', 0)
    }

    if (Info['item_id'] == 1 and Info['order_type'] == 1):
        Info['item_name'] = '一年会员'
    if (Info['item_id'] == 2 and Info['order_type'] == 1):
        Info['item_name'] = '二年会员'
    if (Info['item_id'] == 3 and Info['order_type'] == 1):
        Info['item_name'] = '三年会员'

    if not Info:
        return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})

    try:
        rs, rsJson = OrderDaoV3().insertOrder(Info, order_no)
    except Exception, e:
        return jsonify({"message": {"code": 0, "info": e}})

    if (rs==1):
        return jsonify(
            {"message": {"code": 1, "info": "addOrder OK"}, "rs": rsJson})  #
    else:
        return jsonify({"message": {"code": 0, "info": "addOrder Error"}, "rs": rsJson})  # 添加函数调用失败



@app.route('/updateOrder', methods=['POST'])
def updateOrderNoToken():  #
        if not request.json:
            abort(400)


        try:
            order_id = request.json.get('id')
        except:
            return jsonify({"message": {"code": 0, "status": "请传入 id(order_id)"}})
        oldOrderInfo = OrderDaoV3().selectOrder(order_id)

        newOrderInfo = {

            'order_id': request.json.get('id', oldOrderInfo[0]),
            # 1-4
            'order_no': request.json.get('orderNo', oldOrderInfo[1]),  #
           
            'order_ip': request.remote_addr,  ##确定   读取request
            'order_type': request.json.get('orderType', oldOrderInfo[3]),  #
            'trade_no': request.json.get('tradeNo', oldOrderInfo[4]),

            # 5-9
            'user_id': request.json.get('userId', oldOrderInfo[5]),  #
            'user_name': request.json.get('userName', oldOrderInfo[6]),  #
            'payment_id': request.json.get('paymentId', oldOrderInfo[7]),  #
            'payment_fee': request.json.get('paymentFee', str(oldOrderInfo[8])),
            'payment_status': request.json.get('paymentStatus', oldOrderInfo[9]),

            # 10-14
            'payment_time': request.json.get('paymentTime', oldOrderInfo[10]),  #
            'order_created_time': request.json.get('orderCreatedTime', oldOrderInfo[11]),  #
            'is_invoice': request.json.get('isInvoice', oldOrderInfo[12]),  #
            'invoice_title': request.json.get('invoiceTitle', oldOrderInfo[13]),
            'invoice_taxes': request.json.get('invoiceTaxes', str(oldOrderInfo[14])),

            # 15-19
            'payable_amount': request.json.get('payableAmount', str(oldOrderInfo[15])),  #
            'real_amount': request.json.get('realAmount', str(oldOrderInfo[16])),  #
            'order_amount': request.json.get('orderAmount', str(oldOrderInfo[17])),  #
            'order_point': request.json.get('orderPoint', oldOrderInfo[18]),
            'is_member': request.json.get('isMember', oldOrderInfo[19]),

            # 20-24
            'member_name': request.json.get('memberName', oldOrderInfo[20]),  #
            'member_email': request.json.get('memberEmail', oldOrderInfo[21]),  #
            'member_telephone': request.json.get('memberTelephone', oldOrderInfo[22]),  #
            'member_province': request.json.get('memberProvince', oldOrderInfo[23]),
            'member_city': request.json.get('memberCity', oldOrderInfo[24]),

            # 25-29
            'member_district': request.json.get('memberDistrict', oldOrderInfo[25]),  #
            'member_address': request.json.get('memberAddress', oldOrderInfo[26]),  #
            'is_coupon': request.json.get('isCoupon', oldOrderInfo[27]),  #
            'coupon_name': request.json.get('couponName', oldOrderInfo[28]),
            'coupon_code': request.json.get('couponCode', oldOrderInfo[29]),

            # 30-34
            'coupon_type': request.json.get('couponType', oldOrderInfo[30]),  #
            'coupon_conditions': request.json.get('couponConditions', oldOrderInfo[31]),  #
            'coupon_discount': request.json.get('couponDiscount', oldOrderInfo[32]),  #
            'service_content': request.json.get('serviceContent', oldOrderInfo[33]),
            'service_contract': request.json.get('serviceContract', oldOrderInfo[34]),

            # 35-39
            'service_code': request.json.get('serviceCode', oldOrderInfo[35]),  #
            'service_name': request.json.get('serviceName', oldOrderInfo[36]),  #
            'service_price': request.json.get('servicePrice', str(oldOrderInfo[37])),  #
            'service_rate': request.json.get('serviceRate', str(oldOrderInfo[38])),
            'item_name': request.json.get('itemName', oldOrderInfo[39]),

            # 40-44
            'item_content': request.json.get('itemContent', oldOrderInfo[40]),  #
            'item_url': request.json.get('itemUrl', oldOrderInfo[41]),  #
            'item_address': request.json.get('itemAddress', oldOrderInfo[42]),  #
            'item_publishdate': request.json.get('itemPublishdate', oldOrderInfo[43]),
            'item_deadline': request.json.get('itemDeadline', oldOrderInfo[44]),

            # 45-49
            'item_handlername': request.json.get('itemHandlername', oldOrderInfo[45]),  #
            'item_handlerphone': request.json.get('itemHandlerphone', oldOrderInfo[46]),  #
            'dept_id': request.json.get('deptId', oldOrderInfo[47]),  #
            'order_status': request.json.get('orderStatus', oldOrderInfo[48]),
            'order_product_is_success': request.json.get('orderProductIsSuccess', oldOrderInfo[49]),
            'order_message': request.json.get('orderMessage', oldOrderInfo[50]),
            'item_id': request.json.get('itemId', oldOrderInfo[51]),
            'coupon_id': request.json.get('couponId'),

        }

        if (newOrderInfo['item_id'] == 1 and newOrderInfo['order_type'] == 1):
            newOrderInfo['item_name'] = "一年会员"
        if (newOrderInfo['item_id'] == 2 and newOrderInfo['order_type'] == 1):
            newOrderInfo['item_name'] = "二年会员"
        if (newOrderInfo['item_id'] == 3 and newOrderInfo['order_type'] == 1):
            newOrderInfo['item_name'] = "三年会员"

        if not newOrderInfo:
            return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
        try:
            rs = OrderDaoV3().updateOrder(newOrderInfo)

        except Exception,e:
            return jsonify({"message": {"code": 0, "info": "信息填写错误:"+str(e)}})
        if rs:
            return jsonify({"updateInfo": newOrderInfo, "message": {"code": 1, "info": "updateOrder OK"}})  # 添加函数调用成功，返回添加的信息
        else:
            return jsonify({"message": {"code": 0, "info": "updateOrder Error"}})  # 添加函数调用失败


@app.route('/updateOrder_Old', methods=['POST'])
def updateOrderNoTokenOld():  #
        if not request.json:
            abort(400)


        try:
            order_no = request.json.get('order_no')
        except:
            return jsonify({"message": {"code": 0, "status": "请传入 order_no"}})
        oldInfo = OrderDaoYM().selectOrder(order_no)

        Info = {

            'id': request.json.get('id', oldInfo[0]),
            # 1-4
            'order_no': request.json.get('order_no', oldInfo[1]),  #
            'order_ip': request.json.get('order_ip', oldInfo[2]),  #
            'order_type': request.json.get('order_type', oldInfo[3]),  #
            'trade_no': request.json.get('trade_no', oldInfo[4]),

            # 5-9
            'user_id': request.json.get('user_id', oldInfo[5]),  #
            'user_name': request.json.get('user_name', oldInfo[6]),  #
            'payment_id': request.json.get('payment_id', oldInfo[7]),  #
            'payment_fee': request.json.get('payment_fee', oldInfo[8]),
            'payment_status': request.json.get('payment_status', oldInfo[9]),

            # 10-14
            'payment_time': request.json.get('payment_time', oldInfo[10]),  #
            'order_created_time': request.json.get('order_created_time', oldInfo[11]),  #
            'is_invoice': request.json.get('is_invoice', oldInfo[12]),  #
            'invoice_title': request.json.get('invoice_title', oldInfo[13]),
            'invoice_taxes': request.json.get('invoice_taxes', oldInfo[14]),

            # 15-19
            'payable_amount': request.json.get('payable_amount', oldInfo[15]),  #
            'real_amount': request.json.get('real_amount', oldInfo[16]),  #
            'order_amount': request.json.get('order_amount', oldInfo[17]),  #
            'order_point': request.json.get('order_point', oldInfo[18]),
            'is_member': request.json.get('is_member', oldInfo[19]),

            # 20-24
            'member_name': request.json.get('member_name', oldInfo[20]),  #
            'member_email': request.json.get('member_email', oldInfo[21]),  #
            'member_telephone': request.json.get('member_telephone', oldInfo[22]),  #
            'member_province': request.json.get('member_province', oldInfo[23]),
            'member_city': request.json.get('member_city', oldInfo[24]),

            # 25-29
            'member_district': request.json.get('member_district', oldInfo[25]),  #
            'member_address': request.json.get('member_address', oldInfo[26]),  #
            'is_coupon': request.json.get('is_coupon', oldInfo[27]),  #
            'coupon_name': request.json.get('coupon_name', oldInfo[28]),
            'coupon_code': request.json.get('coupon_code', oldInfo[29]),

            # 30-34
            'coupon_type': request.json.get('coupon_type', oldInfo[30]),  #
            'coupon_conditions': request.json.get('coupon_conditions', oldInfo[31]),  #
            'coupon_discount': request.json.get('coupon_discount', oldInfo[32]),  #
            'service_content': request.json.get('service_content', oldInfo[33]),
            'service_contract': request.json.get('service_contract', oldInfo[34]),

            # 35-39
            'service_code': request.json.get('service_code', oldInfo[35]),  #
            'service_name': request.json.get('service_name', oldInfo[36]),  #
            'service_price': request.json.get('service_price', oldInfo[37]),  #
            'service_rate': request.json.get('service_rate', oldInfo[38]),
            'item_name': request.json.get('item_name', oldInfo[39]),

            # 40-44
            'item_content': request.json.get('item_content', oldInfo[40]),  #
            'item_url': request.json.get('item_url', oldInfo[41]),  #
            'item_address': request.json.get('item_address', oldInfo[42]),  #
            'item_publishdate': request.json.get('item_publishdate', oldInfo[43]),
            'item_deadline': request.json.get('item_deadline', oldInfo[44]),

            # 45-49
            'item_handlername': request.json.get('item_handlername', oldInfo[45]),  #
            'item_handlerphone': request.json.get('item_handlerphone', oldInfo[46]),  #
            'dept_id': request.json.get('dept_id', oldInfo[47]),  #
            'order_status': request.json.get('order_status', oldInfo[48]),
            'order_product_is_success': request.json.get('order_product_is_success', oldInfo[49]),
            'order_message': request.json.get('order_message', oldInfo[50])

        }
        if not Info:
            return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
        try:
            rs = OrderDaoYM().updateOrder(Info)
        except:
            return jsonify({"message": {"code": 0, "info": "信息填写错误"}})
        if rs:
            return jsonify({"addInfo": Info, "message": {"code": 1, "info": "updateOrder OK"}})  # 添加函数调用成功，返回添加的信息
        else:
            return jsonify({"message": {"code": 0, "info": "updateOrder Error"}})  # 添加函数调用失败



@app.route('/deleteOrder', methods=['DELETE', 'POST'])  # 根据id数组删除zzh_user_Code表指定记录,传入格式为 "ids":[1,2,3,4]
def deleteOrder():
    ids = request.json.get("ids")
    if not ids:
        return jsonify({"message": "请输入待删除的  id数组！"})
    try:
        rs = OrderDaoYM().deleteOrder(ids)
    except:
        return jsonify({"message":"指定的orderId不存在"})
    if rs:
        return jsonify({"message": {"code": 1, "info": "deleteOrder OK"}})
    else:
        return jsonify({"message": {"code": 0, "info": "deleteOrder Error"}})




@app.route('/removeOrder', methods=['POST'])  # 根据id数组删除zzh_user_Code表指定记录,传入格式为 "ids":[1,2,3,4]
def removeOrder():
    ids = request.json.get("ids")
    userId = request.json.get("userId")
    if not ids and userId:
        return jsonify({"message": "缺少参数 ids(数组格式)和 userId"})
    try:
        rs = OrderDaoYM().removeOrder(ids, userId)
    except:
        return jsonify({"message":"指定的orderId或者userId不存在"})
    if rs:
        return jsonify({"message": {"code": 1, "info": "logicDeleteOrder OK"}})
    else:
        return jsonify({"message": {"code": 0, "info": "logicDeleteOrder Error"}})

